<template>
  <div class="mcp-service-manager" :class="{ 'dark': isDark }">
    <!-- 头部工具栏 -->
    <div class="manager-header">
      <div class="header-left">
        <h2 class="manager-title">MCP 服务管理</h2>
        <el-tag :type="statusTagType" effect="plain">
          {{ services.length }} 个服务
        </el-tag>
      </div>
      <div class="header-actions">
        <el-button :icon="Plus" type="primary" @click="showAddDialog">
          添加服务
        </el-button>
        <el-button :icon="Refresh" :loading="isRefreshing" @click="refreshServices">
          刷新
        </el-button>
      </div>
    </div>

    <!-- 过滤器和搜索 -->
    <div class="manager-filters">
      <el-input
        v-model="searchQuery"
        placeholder="搜索服务名称"
        :prefix-icon="Search"
        clearable
        style="width: 300px"
      />
      <el-select
        v-model="statusFilter"
        placeholder="状态筛选"
        clearable
        style="width: 150px"
      >
        <el-option label="全部" value="" />
        <el-option label="活跃" value="active" />
        <el-option label="停用" value="inactive" />
        <el-option label="错误" value="error" />
      </el-select>
    </div>

    <!-- 服务列表 -->
    <div class="services-content">
      <el-empty v-if="filteredServices.length === 0" description="暂无服务">
        <el-button type="primary" @click="showAddDialog">添加第一个服务</el-button>
      </el-empty>

      <div v-else class="services-grid">
        <div
          v-for="service in filteredServices"
          :key="service.id"
          class="service-card"
          :class="`status-${service.status}`"
        >
          <div class="service-header">
            <div class="service-info">
              <h3 class="service-name">{{ service.name }}</h3>
              <el-tag :type="getStatusTagType(service.status)" size="small">
                {{ getStatusText(service.status) }}
              </el-tag>
            </div>
            <div class="service-actions">
              <el-button
                :icon="VideoPlay"
                size="small"
                type="success"
                @click="testService(service)"
                :loading="testingServices.has(service.id)"
              >
                测试
              </el-button>
              <el-button :icon="Edit" size="small" @click="showEditDialog(service)">
                编辑
              </el-button>
              <el-button
                :icon="Delete"
                size="small"
                type="danger"
                @click="deleteService(service)"
              >
                删除
              </el-button>
            </div>
          </div>

          <div class="service-description">
            <p>{{ service.description || '暂无描述' }}</p>
          </div>

          <div class="service-details">
            <div class="detail-item">
              <span class="detail-label">端点:</span>
              <span class="detail-value">{{ service.endpoint }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">方法:</span>
              <div class="method-tags">
                <el-tag
                  v-for="method in service.methods.slice(0, 3)"
                  :key="method"
                  size="small"
                  effect="plain"
                >
                  {{ method }}
                </el-tag>
                <el-tag
                  v-if="service.methods.length > 3"
                  size="small"
                  type="info"
                >
                  +{{ service.methods.length - 3 }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑服务对话框 -->
    <el-dialog
      v-model="serviceDialog.visible"
      :title="serviceDialog.isEdit ? '编辑服务' : '添加服务'"
      width="600px"
    >
      <el-form
        ref="serviceFormRef"
        :model="serviceForm"
        :rules="serviceFormRules"
        label-width="100px"
      >
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="serviceForm.name" placeholder="请输入服务名称" />
        </el-form-item>
        
        <el-form-item label="服务描述" prop="description">
          <el-input
            v-model="serviceForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入服务描述"
          />
        </el-form-item>
        
        <el-form-item label="服务端点" prop="endpoint">
          <el-input v-model="serviceForm.endpoint" placeholder="https://api.example.com" />
        </el-form-item>
        
        <el-form-item label="支持方法" prop="methods">
          <div class="methods-input">
            <el-tag
              v-for="method in serviceForm.methods"
              :key="method"
              closable
              @close="removeMethod(method)"
            >
              {{ method }}
            </el-tag>
            <el-input
              v-if="showMethodInput"
              ref="methodInputRef"
              v-model="newMethod"
              size="small"
              style="width: 120px"
              @keyup.enter="addMethod"
              @blur="addMethod"
            />
            <el-button
              v-else
              size="small"
              type="primary"
              plain
              @click="showAddMethod"
            >
              + 添加方法
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="服务状态" prop="status">
          <el-radio-group v-model="serviceForm.status">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="inactive">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="serviceDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="isSaving" @click="saveService">
          {{ serviceDialog.isEdit ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useUIStore } from '@/stores/ui'
import { useAPIService } from '@/services/api'
import {
  Plus,
  Refresh,
  Search,
  VideoPlay,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import type { MCPService } from '@/types'

const uiStore = useUIStore()
const { isDark } = storeToRefs(uiStore)
const apiService = useAPIService()

// 响应式数据
const services = ref<MCPService[]>([])
const isRefreshing = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const testingServices = ref<Set<string>>(new Set())

const serviceDialog = ref({
  visible: false,
  isEdit: false
})

const serviceForm = ref<Partial<MCPService>>({
  name: '',
  description: '',
  endpoint: '',
  methods: [],
  status: 'active'
})

const newMethod = ref('')
const showMethodInput = ref(false)
const isSaving = ref(false)
const serviceFormRef = ref<FormInstance>()
const methodInputRef = ref<HTMLInputElement>()

// 表单验证规则
const serviceFormRules: FormRules = {
  name: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  endpoint: [
    { required: true, message: '请输入服务端点', trigger: 'blur' }
  ],
  methods: [
    { required: true, message: '请至少添加一个方法', trigger: 'change' }
  ]
}

// 计算属性
const statusTagType = computed(() => {
  const activeCount = services.value.filter(s => s.status === 'active').length
  const total = services.value.length
  if (total === 0) return 'info'
  if (activeCount === total) return 'success'
  if (activeCount === 0) return 'danger'
  return 'warning'
})

const filteredServices = computed(() => {
  let result = services.value

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(service =>
      service.name.toLowerCase().includes(query) ||
      service.description?.toLowerCase().includes(query)
    )
  }

  if (statusFilter.value) {
    result = result.filter(service => service.status === statusFilter.value)
  }

  return result
})

// 方法
const getStatusTagType = (status: string): string => {
  const typeMap = {
    active: 'success',
    inactive: 'info',
    error: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string): string => {
  const textMap = {
    active: '活跃',
    inactive: '停用',
    error: '错误'
  }
  return textMap[status] || status
}

const loadServices = async () => {
  try {
    isRefreshing.value = true
    const data = await apiService.getMCPServices()
    services.value = data
  } catch (error) {
    console.error('Failed to load services:', error)
    ElMessage.error('加载服务失败')
  } finally {
    isRefreshing.value = false
  }
}

const refreshServices = () => {
  loadServices()
}

const showAddDialog = () => {
  serviceForm.value = {
    name: '',
    description: '',
    endpoint: '',
    methods: [],
    status: 'active'
  }
  serviceDialog.value = {
    visible: true,
    isEdit: false
  }
}

const showEditDialog = (service: MCPService) => {
  serviceForm.value = { ...service }
  serviceDialog.value = {
    visible: true,
    isEdit: true
  }
}

const saveService = async () => {
  if (!serviceFormRef.value) return

  try {
    await serviceFormRef.value.validate()
    isSaving.value = true

    if (serviceDialog.value.isEdit) {
      await apiService.updateMCPService(serviceForm.value.id!, serviceForm.value)
      ElMessage.success('服务更新成功')
    } else {
      await apiService.createMCPService(serviceForm.value as Omit<MCPService, 'id' | 'createdAt' | 'updatedAt'>)
      ElMessage.success('服务添加成功')
    }

    serviceDialog.value.visible = false
    await loadServices()

  } catch (error) {
    console.error('Failed to save service:', error)
    ElMessage.error('保存服务失败')
  } finally {
    isSaving.value = false
  }
}

const testService = async (service: MCPService) => {
  try {
    testingServices.value.add(service.id)
    const result = await apiService.testMCPService(service.id)
    
    if (result.success) {
      ElMessage.success(`服务测试成功，响应时间: ${result.responseTime}ms`)
    } else {
      ElMessage.error(`服务测试失败: ${result.error}`)
    }
  } catch (error) {
    console.error('Failed to test service:', error)
    ElMessage.error('服务测试失败')
  } finally {
    testingServices.value.delete(service.id)
  }
}

const deleteService = async (service: MCPService) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除服务 "${service.name}" 吗？`,
      '确认删除',
      { type: 'warning' }
    )

    await apiService.deleteMCPService(service.id)
    ElMessage.success('服务删除成功')
    await loadServices()

  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete service:', error)
      ElMessage.error('删除服务失败')
    }
  }
}

const showAddMethod = async () => {
  showMethodInput.value = true
  await nextTick()
  methodInputRef.value?.focus()
}

const addMethod = () => {
  if (newMethod.value && !serviceForm.value.methods?.includes(newMethod.value)) {
    serviceForm.value.methods = serviceForm.value.methods || []
    serviceForm.value.methods.push(newMethod.value)
    newMethod.value = ''
  }
  showMethodInput.value = false
}

const removeMethod = (method: string) => {
  if (serviceForm.value.methods) {
    const index = serviceForm.value.methods.indexOf(method)
    if (index > -1) {
      serviceForm.value.methods.splice(index, 1)
    }
  }
}

// 组件挂载时加载数据
loadServices()
</script>

<style scoped lang="scss">
.mcp-service-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);

  &.dark {
    background: var(--el-bg-color-darker);
  }
}

.manager-header {
  padding: 20px 24px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    .manager-title {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.manager-filters {
  padding: 16px 24px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  display: flex;
  gap: 12px;
  align-items: center;
}

.services-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.services-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.service-card {
  padding: 20px;
  background: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  transition: all 0.2s ease;

  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &.status-active {
    border-left: 4px solid var(--el-color-success);
  }

  &.status-inactive {
    border-left: 4px solid var(--el-color-info);
  }

  &.status-error {
    border-left: 4px solid var(--el-color-danger);
  }
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;

  .service-info {
    flex: 1;

    .service-name {
      margin: 0 0 8px 0;
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }

  .service-actions {
    display: flex;
    gap: 8px;
  }
}

.service-description {
  margin-bottom: 16px;

  p {
    margin: 0;
    color: var(--el-text-color-regular);
    font-size: 14px;
    line-height: 1.5;
  }
}

.service-details {
  .detail-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-size: 14px;

    &:last-child {
      margin-bottom: 0;
    }

    .detail-label {
      min-width: 50px;
      color: var(--el-text-color-regular);
    }

    .detail-value {
      flex: 1;
      color: var(--el-text-color-primary);
      word-break: break-all;
    }

    .method-tags {
      display: flex;
      gap: 4px;
      flex-wrap: wrap;
    }
  }
}

.methods-input {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}
</style>